package cn.yh.nft.turbo.user.domain.service.impl;

import cn.yh.nft.turbo.base.utils.HttpUtils;
import cn.yh.nft.turbo.user.domain.service.AuthService;
import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;

import java.util.Map;

/**
 * @ClassName: AuthServiceImpl
 * @Author: 草莓爱上啵啵
 *
 *  认证服务
 */
@Slf4j
public class AuthServiceImpl implements AuthService {

    private String host;

    private String path;

    private String appcode;

    private static final String CODE = "code";

    public AuthServiceImpl(String host, String path, String appcode){
        this.host = host;
        this.path = path;
        this.appcode = appcode;
    }

    /**
     * 实名认证
     * @param realName 用户名
     * @param idCard   身份证号
     * @return
     */
    @Override
    public boolean checkAuth(String realName, String idCard) {
        String method ="POST";

        Map<String, String> headers = Maps.newHashMapWithExpectedSize(2);
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求， 定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = Maps.newHashMapWithExpectedSize(2);
        Map<String, String> bodys = Maps.newHashMapWithExpectedSize(2);

        bodys.put("idcard", idCard);
        bodys.put("name", realName);


        try{
            var response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            Map<String, Object> resultMap = JSON.parseObject(EntityUtils.toString(response.getEntity()), Map.class);

            log.info("auth result : " + resultMap);

            if (!CollectionUtils.isEmpty(resultMap) && resultMap.get(CODE) != null && (Integer) resultMap.get(CODE) == 200) {
                Map<String, Object> dataMap = (Map<String, Object>) resultMap.get("data");
                // 将 data 数据放入 Map 集合中进行后续操作
                if (!CollectionUtils.isEmpty(dataMap)) {
                    // 示例：获取 data 中的字段值
                    Integer result = (Integer) dataMap.get("result");
                    return result == 0;
                }

            }
            return false;

        } catch (Exception e){
            log.error("checkAuth error realName=" + realName, e);
        }
        return false;
    }
}
